﻿#include "mysql.h"

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char *g_strVersion = "1.0.0.0";

//日志文件的原始名字
//从APP上传得到
char g_strFilePathName[256] = { 0 };

//由日志文件名字获得的日志数据表名字
char g_strTableName[256] = { 0 };

//由日志文件获得的机器人序列号
char g_strRobotSerial[256] = { 0 };

//根据机器人序列号查找到的机器人ID
int nRobotID = 0;

//print usage
void usage()
{
    printf("Usage:\n");
    printf("-h      print usage\r\n");
    printf("-v      print version\r\n");
    printf("-i      input file\r\n");

    printf("end help\r\n");
}

//parse_args
int parse_args(int argc, char** argv)
{
		int argn = 1;
    if (argn >= argc)
    {
        usage();
        return 1;
    }

    while (argn < argc)
    {
        if (strcmp(argv[argn], "-v") == 0)
        {
        	printf("%s", g_strVersion);
        	return 1;
        }
        else if (strcmp(argv[argn], "-i") == 0)
        {
        	argn++;
        	if( argn < argc)
        	{
        		sprintf(g_strFilePathName, "%s", argv[argn]);
        	}
        	else
        	{
        		printf("parameter error\r\n");
        		return 1;
        	}
        }
        else
        {
        	usage();
        	return 1;
        }

        ++argn;
    }

    return 0;
}

int GetRobotIDBySerial(char *pRobotSerial)
{
	char strSQL[256] = { 0 };
	int nID = 0;
			//连接数据库
		MYSQL mysql;
		MYSQL_RES *result = NULL;
		mysql_init(&mysql);
		bool bConnected = mysql_real_connect(&mysql, "localhost", "fanyiping", "@Bc12345", "pd_cloud", 3306, NULL, 0);
		if( bConnected == false )
		{
			printf("%s", "connect db failed.\n");
			return -1;
		}
				
		//由机器人的序列号查询到机器人ID
		//如果机器人序列号不存在，就添加一条记录
		//并返回新建的ID
		sprintf(strSQL, "select pid, code from pd_robotcode where code = '%s'", pRobotSerial);
		
		mysql_query(&mysql, strSQL);
    result = mysql_store_result(&mysql);
    
    int rowcount = mysql_num_rows(result);
    if( rowcount == 0 )
    {
    	//insert robot serial return id
    	memset(strSQL, 0 , 256);
    	sprintf(strSQL, "insert into pd_robotcode(code) values('%s')", pRobotSerial);
    	
    	 if(mysql_query(&mysql,strSQL))
 			{
  			printf("执行insert失败%s\n",mysql_error(&mysql));
  			mysql_close(&mysql);
  			return -1;
 			}
 			
 			nID = mysql_insert_id(&mysql);
 			mysql_close(&mysql);
 			return nID;
    }
    	
    MYSQL_ROW sql_row = NULL;
    sql_row=mysql_fetch_row(result);
    	
    nID = atoi(sql_row[0]);
    mysql_close(&mysql);
    	
		return nID;
}

//提交的日志文件名字格式：
//20160830-xxxx-APP-Log.txt
//时间-机器人序列号-日志类型-Log.txt
//日志类型确定数据要导入的表
int ParserDataFromFileName()
{
		char strFilePathName[256] = { 0 };
		char strSQL[256] = { 0 };
		const char *delim = "-";
		
		char *pDateDate = NULL;
		char *pRobotSerialID = NULL;
		char *pLogType = NULL;
		
		int nLen = strlen(g_strFilePathName);
		if(nLen <= 0 )
		{
			return -1;
		}
		
		memcpy(strFilePathName, g_strFilePathName, nLen );
		
		pDateDate = strtok(strFilePathName , delim);
		pRobotSerialID = strtok(NULL , delim);
		pLogType = strtok(NULL , delim);

		if(strcmp(pLogType, "APP") == 0)
		{
			strcpy(g_strTableName, "pd_information");
		}
		else if(strcmp(pLogType, "CANUPLOAD") == 0)
		{
			strcpy(g_strTableName, "pd_can_upload_data");
		}
		else if(strcmp(pLogType, "CANDOWNLOAD") == 0)
		{
			strcpy(g_strTableName, "pd_can_download_data");
		}
		
		printf("%s\n", pDateDate);
		printf("%s\n", pRobotSerialID);
		printf("%s\n", pLogType);
		
		nRobotID = GetRobotIDBySerial(pRobotSerialID);
    
		return nRobotID;
}

//连接数据库，把日志文件导入的数据库表
void ImportData()
{
	FILE *fp;
	char Line[1024] = {0};
	char strInsertSQL[1024] = {0};

	if ((fp=fopen(g_strFilePathName,"rb+"))==NULL)
	{
		printf("Open Failed.\n");
		return;
	}
	
	//连接数据库
	MYSQL mysql;
	MYSQL_RES *result = NULL;
	mysql_init(&mysql);
	bool bConnected = mysql_real_connect(&mysql, "localhost", "fanyiping", "@Bc12345", "pd_cloud", 3306, NULL, 0);
	if( bConnected == false )
		{
			printf("%s", "connect db failed.\n");
			return;
		}

	char *pDateDate = NULL;
	char *pLongDate = NULL;
	char *pValueDate = NULL;
	
	const char *delim = "\t";

	while(fgets (Line, 1024, fp) != NULL)
	{
		printf("%s", Line);

		//分割字符串
		pDateDate = strtok(Line , delim);
		pLongDate = strtok(NULL , delim);
		pValueDate = strtok(NULL , delim);
		if( pDateDate == NULL || pLongDate == NULL || pValueDate == NULL
			|| strlen(pDateDate) == 0 || strlen(pLongDate) == 0 || strlen(pValueDate) == 0)
			{
				continue;
			}
		
		sprintf(strInsertSQL, "INSERT INTO %s(logtime, contents, pid) VALUES(%s, '%s', %d)", g_strTableName, pLongDate, pValueDate, nRobotID);
		
		mysql_query(&mysql, strInsertSQL);
		
		memset(strInsertSQL, 0, 1024);
		memset(Line, 0, 1024);

		continue;
	}
	
	mysql_close(&mysql);
}

//main
int main(int argc, char** argv)
{
	//解析命令行
	if (parse_args(argc, argv) != 0)
	{
		goto error;
	}
	
	//从文件名字解析机器人ID和要导入的表名字
	if( ParserDataFromFileName()<=0 )
		{
			goto error;
		}

	//连接数据库,导入表
  ImportData();

	return 0;

error:
  return 1;
}